package models

import (
	"context"
	"github.com/beego/beego/v2/client/orm"
	"time"
)

type Setting struct {
	BModel
	Field string `json:"field" orm:"column(field)" form:"field"`
	Value string `json:"value" orm:"column(value)" form:"value"`
}

func NewSetting() *Setting {
	return &Setting{}
}

func (*Setting) TableName() string {
	return SettingTable
}

type SetReq struct {
	Field string `json:"field" orm:"column(field)"`
	Value string `json:"value" orm:"column(value)"`
}

func (tb *Setting) GetMap() (m map[string]string) {

	db := orm.NewOrm()
	m = make(map[string]string, 0)
	var lst []Setting
	q := db.QueryTable(tb)
	q.All(&lst)
	for _, v := range lst {
		m[v.Field] = v.Value
	}
	return

}

func (tb *Setting) SaveBatch(m map[string]string, uid uint64) error {

	if m == nil || len(m) <= 0 {
		return nil
	}

	db := orm.NewOrm()
	now := time.Now()
	return db.DoTx(func(ctx context.Context, txOrm orm.TxOrmer) error {
		for k, v := range m {
			tb.UpdatedAt = now
			tb.CreatedAt = now
			tb.CreatedBy = uid
			tb.UpdatedBy = uid
			tb.Field = k
			tb.Value = v
			tb.ID = 0
			if _, e := txOrm.Delete(tb, "field"); e != nil {
				return e
			}
			if _, e := txOrm.Insert(tb); e != nil {
				return e
			}

		}
		return nil
	})

}
